package com.github.zhangkaitao.shiro.chapter15.realm;

import com.github.zhangkaitao.shiro.chapter15.service.UserService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-2-13
 * <p>Version: 1.0
 */
public class MyCasRealm extends CasRealm {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * liuyifan<br/>
     * 如果授权服务（器）和本客户端（即本应用系统sso客户端）（服务器）不在一台物理主机上，需要远程授权服务器提供用户角色和权限信息的查询接口（或远程调用）<br/>
     * 即替换下面方法中：userService.findRoles(username)和userService.findPermissions(username)为远程调用<br/>
     * 没有单点登录情况下的话，登录认证和授权认证默认在AuthorizingRealm的doGetAuthorizationInfo和doGetAuthenticationInfo中进行，所以我这里是通过shiroDbRealm（继承AuthorizingRealm的自定义类）覆写doGetAuthorizationInfo和doGetAuthenticationInfo，实现自定义登录认证和授权认证。<br/>
     * 有单点登录情况下，登录认证是在casserver进行的，那么执行流程是这样的：用户从 cas server登录成功后，跳到cas client的CasRealm执行默认的doGetAuthorizationInfo和doGetAuthenticationInfo，此时doGetAuthenticationInfo做的工作是把登录用户信息传递给shiro，保持默认即可，而对于授权的处理，可以通过MyCasRealm（继承CasRealm的自定义类）覆写doGetAuthorizationInfo进行自定义授权认证。<br/>
     * 参考网址：http://blog.csdn.net/tch918/article/details/22311747<br/>
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.findRoles(username));
        authorizationInfo.setStringPermissions(userService.findPermissions(username));

        return authorizationInfo;
    }
}
